package com.mashiguang.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.authentication.encoding.PasswordEncoder;

public class DatabasePasswordSecurerBean extends JdbcDaoSupport {
	
	private static Logger log = LoggerFactory.getLogger(DatabasePasswordSecurerBean.class);

	private PasswordEncoder passwordEncoder;
	
	public void securePassword(){
		getJdbcTemplate().query("select username,password from users", 
				new RowCallbackHandler() {
					
					public void processRow(ResultSet rs) throws SQLException {
						String username = rs.getString(1);
						String password = rs.getString(2);
						String securePassword = passwordEncoder.encodePassword(password, null);
						
						getJdbcTemplate().update("update users set password = ?" +
								" where username = ?",securePassword,username);
						
						log.debug("update {}'s password to {}",
								username,securePassword);
					}
				});
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}
}
